#import "KeyValueValidation.h"

static NSDictionary *validateValuesInDictionary(id object, NSDictionary *values)
{
    NSEnumerator *editEnum = [values keyEnumerator];
    NSMutableDictionary *errorDict = nil;
    NSString *key;

    while (key = [editEnum nextObject]) {
        // construct a selector and see if the have a validation method
        id value = [values objectForKey:key];
        NSString *methodName = [NSString stringWithFormat:@"validate%@:", [key capitalizedString]];
        SEL selector = sel_getUid([methodName cString]);
        NSString *errorMessage = nil;

        if (selector && [object respondsToSelector:selector]) {
            errorMessage = [object perform:selector withObject:value];
            if (errorMessage) {
                if (!errorDict)
                    errorDict = [NSMutableDictionary dictionary];
                [errorDict setObject:errorMessage forKey:key];
            }
        }
    }
    return errorDict;
}

@implementation NSObject (KeyValueValidation)
- (NSDictionary *)validateValuesInDictionary:(NSDictionary *)values
{
    return validateValuesInDictionary(self, values);
}
@end

